package cn.aishua.network;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

public abstract class DownloadPicAsyncTask
    extends AsyncTask<String, Void, Bitmap>
{

    @Override
    protected Bitmap doInBackground( String... params )
    {
        HttpURLConnection conn = null;
        Bitmap bitmap = null;
        Log.d( "DownloadPicAsyncTask", "url: " + params[0] );
        try
        {
            URL url = new URL( params[0] );
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput( true );
            conn.connect();
            InputStream inputStream = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream( inputStream );

        }
        catch( MalformedURLException e1 )
        {
            Log.e( "DownloadPicAsyncTask", e1.getMessage() );
        }
        catch( IOException e )
        {
            Log.e( "DownloadPicAsyncTask", e.getMessage() );
        }
        finally
        {
            conn.disconnect();
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute( Bitmap result )
    {
        if( result != null )
        {
            handlePic( result );
        }
    }

    abstract protected void handlePic( Bitmap bitMap );

}
